<template>
  <div class="con">
    <div class="contbox6_10">
      <p class="titlelist6_10">
        商城管理
        <span style="color: #999">&nbsp;&nbsp;/&nbsp;&nbsp;</span
        >{{ titles }}商品
      </p>
      <div class="content">
        <el-form :model="form" :rules="rules" ref="form" label-width="120px">
          <div style="padding-top: 20px; float: left">
            <el-col>
              <el-form-item label="业务类型" prop="busUid">
                <el-select
                  style="width: 300px"
                  :disabled="sign"
                  v-model="form.busUid"
                  @change="bussType"
                  placeholder="请选择商品品牌"
                  class="filter-item"
                >
                  <el-option
                    v-for="item in busOptions"
                    :key="item.busUid"
                    :label="item.busName"
                    :value="item.busUid"
                  ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="业务品牌" prop="channelUid">
                <el-select
                  style="width: 300px"
                  :disabled="sign"
                  v-model="form.channelUid"
                  placeholder="请选择商品品牌"
                  class="filter-item"
                >
                  <el-option
                    v-for="item in channelNameList2"
                    :key="item.channelUid"
                    :label="item.channelName"
                    :value="item.channelUid"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="商品类型" prop="channelType">
                <el-cascader
                  :disabled="sign"
                  v-model="form.channelType"
                  :options="options"
                  :props="{ emitPath: false }"
                ></el-cascader>
              </el-form-item>
              <el-form-item label="商品型号" prop="productNo">
                <el-input
                  v-model="form.productNo"
                  :disabled="sign"
                  maxlength="20"
                  placeholder="请输入商品型号"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item label="商品名称" prop="productName">
                <el-input
                  v-model="form.productName"
                  :disabled="sign"
                  maxlength="30"
                  placeholder="请输入商品名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="商品原价" prop="marketAmt">
                <el-input
                  style="width: 250px"
                  v-model="form.marketAmt"
                  :disabled="sign"
                  @input="
                    (value) => {
                      form.marketAmt = value.replace(
                        /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                        '$1'
                      );
                    }
                  "
                  maxlength="10"
                  placeholder="请输入商品原价"
                >
                </el-input
                ><span style="margin-left: 60px">元</span>
              </el-form-item>

              <el-form-item label="商品售价" prop="unitAmt">
                <el-input
                  style="width: 250px"
                  v-model="form.unitAmt"
                  @input="
                    (value) => {
                      form.unitAmt = value.replace(
                        /^\D*(\d*(?:\.\d{0,2})?).*$/g,
                        '$1'
                      );
                    }
                  "
                  maxlength="10"
                  :disabled="sign"
                  placeholder="请输入商品售价"
                >
                </el-input
                ><span style="margin-left: 60px">元</span>
              </el-form-item>
            </el-col>
            <el-col>
              <!-- <el-form-item label="开通金额" prop="openAmt">
                <el-input
                  style="width:250px"
                  v-model="form.openAmt"
                  :disabled="sign"
                  maxlength="10"
                  @input="value=>{form.openAmt=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')}"
                  placeholder="POS交易开通金额"
                >
                </el-input
                ><span style="margin-left:60px">元</span>
              </el-form-item> -->

              <!-- <el-form-item label="上架控制">
                <el-select
                  v-model="form.upCntCtl"
                  :disabled="sign"
                  @change="$forceUpdate()"
                  placeholder="请选择"
                >
                  <el-option label="保持一致" value="0"></el-option>
                  <el-option label="不必一致" value="1"></el-option> </el-select
                ><el-dropdown placement="bottom-start">
                  <span class="el-dropdown-link">
                    <img src="../../assets/images/sm.png" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item
                      >说明： 选项1：保持一致<br />
                      在售商品与APP用户可购买商品数量一致，即上架售卖中的商品不可以大于<br />库存数量
                      <br />举例：库存总量100；上架数量区间0~100；可购买数量0~100<br />
                      选项2：不必一致<br />
                      在售商品与APP用户可购买商品数量不一致，即上架售卖中的商品数量可以大
                      于库存数量，不受限制
                      <br />举例：库存总量100；上架数量区间0~X；可购买数量0~X</el-dropdown-item
                    >
                  </el-dropdown-menu>
                </el-dropdown>
              </el-form-item> -->
            </el-col>
            <el-form-item label="商品描述" prop="productDesc">
              <el-input
                type="textarea"
                :disabled="sign"
                maxlength="100"
                v-model="form.productDesc"
                placeholder="请输入商品描述"
              ></el-input>
            </el-form-item>
          </div>
          <div style="float: left; width: 96%; margin-left: 29px">
            <p>
              <span style="color: red">*</span>
              商品预览图：尺寸345px*140px(图片大小建议不超过1M，请至少上传1张图片，最多可配置3张）
            </p>
            <div style="margin-left: 93px; margin-top: 20px">
              <el-upload
                :class="uploadDisabled"
                :disabled="sign"
                :action="httpurl + '/api/fileUpload'"
                list-type="picture-card"
                :file-list="form.previewPhotos"
                :limit="3"
                name="file"
                :before-upload="handleUpdate"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-success="success"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="" />
              </el-dialog>
            </div>
          </div>
          <div
            style="float: left; width: 96%; margin-left: 29px; margin-top: 20px"
          >
            <p>
              <span style="color: red">*</span>
              商品详情图：（图片大小建议不超过1M，请至少上传1张图片，最多可配置10张）
            </p>
            <div style="margin-left: 93px; margin-top: 20px">
              <el-upload
                :class="uploadDisableds"
                :disabled="sign"
                :action="httpurl + '/api/fileUpload'"
                list-type="picture-card"
                :file-list="form.detailPhoto"
                :limit="10"
                name="file"
                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
                :on-preview="handlePictureCardPreview1"
                :on-remove="handleRemove1"
                :before-upload="handleUpdate1"
                :on-success="success1"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible1">
                <img width="100%" :src="dialogImageUrl1" alt="" />
              </el-dialog>
            </div>
          </div>
        </el-form>
        <div class="buttons">
          <el-button
            v-if="sign != true"
            style="float: left; margin-left: 40%"
            type="primary"
            @click="complete()"
            >完成</el-button
          >
          <el-button
            v-if="sign != true"
            style="float: left; margin-left: 10px"
            @click="back()"
            >取消</el-button
          >
          <el-button
            v-if="sign == true"
            style="float: left; margin-left: 40%"
            @click="back()"
            >返回</el-button
          >
        </div>
      </div>
    </div>
  </div>
</template>
<script>
var unitAmts = (rule, value, callback) => {
  var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
  if (value) {
    if (reg.test(value)) {
      return callback();
    } else {
      return callback(new Error("请输入正确的金额"));
    }
  } else {
    return callback(new Error("请输入金额"));
  }
};

import https from "../../plugins/https";
export default {
  data() {
    return {
      titles: this.$route.query.titles,
      busOptions:"",
      options: [],
      uploadDisabled: "",
      uploadDisableds: "",
      dialogVisible: false,
      dialogImageUrl: "",
      dialogVisible1: false,
      dialogImageUrl: "",
      httpurl: this.GLOBAL.httpurl,
      channelNameList: [],
      channelTypeList: [],
      channelTypeLists: [],
      aa: "",
      form: {
        openAmt: 0,
        busUid: "", //业务类型
        oemUid: localStorage.getItem("uid"), //OEMid
        productUid: this.$route.query.productUid, //产品id
        channelName: undefined,
        channelUid: undefined, //	品牌Uid
        productName: undefined, //	产品名称
        productType: undefined, //	品牌类型
        channelType: undefined,
        productNo: undefined, //	产品型号
        productDesc: undefined, //	产品描述
        unitAmt: undefined, //	设备单价
        marketAmt: undefined, //
        previewPhotos: [], //	预览图片集合
        status: undefined, //	图片状态
        detailPhoto: [], //	详情图片集合
        photoId: undefined, //	图片id
        photoPath: undefined, //	图片路径
        operaType: undefined, //	操作类型
      },
      channelNameList2:"",
      sign: this.$route.query.type == "2" ? true : false,
      rules: {
        // openAmt: [{ required: true, message: "请输入开通金额，最小为0" }],
        busUid:[{ required: true, message: "请选择业务类型" }],
        channelUid: [{ required: true, message: "请选择品牌名称" }],
        channelType: [{ required: true, message: "请选择商品类型" }],
        productNo: [{ required: true, message: "请输入商品型号" }],
        productName: [{ required: true, message: "请输入商品名称" }],
        unitAmt: [
          { required: true, message: "请输入商品售价" },
          {
            equired: true,
            validator: unitAmts,
            message: "请输入正确商品售价",
            trigger: "blur",
          },
        ],
        marketAmt: [
          { required: true, message: "请输入商品原价" },
          {
            equired: true,
            validator: unitAmts,
            message: "请输入正确商品原价",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.geBusInfo()
    let that = this;
    that.channelNameList = [];
    // 品牌名称
    https.channelNameList({ oemUid: that.form.oemUid }).then((res) => {
      if (res.data.code == "0000") {
        that.channelNameList = res.data.data;
      } else {
        layer.open({
          content: d.data.msg,
          skin: "msg",
          time: 2, //1秒后自动关闭
        });
      }
    });
    https.shopLister({ oemUid: that.form.oemUid }).then((res) => {
      if (res.data.code == "0000") {
        that.options = res.data.data;
      } else {
        layer.open({
          content: d.data.msg,
          skin: "msg",
          time: 2, //1秒后自动关闭
        });
      }
    });
    if (that.$route.query.type == 2) {
      this.uploadDisabled = "disabled";
      this.uploadDisableds = "disabled";
    }
    if (that.$route.query.productUid) {
      
      https
        .echoShopData({ productUid: that.$route.query.productUid })
        .then((res) => {
          if (res.data.code == "0000") {
            that.form = res.data.data;
            console.log(that.form);
            that.aa = that.form.channelType;
            https
              .echoShop({ id: that.form.id })
              .then((res) => {
                if (res.data.code == "0000") {
                  that.channelTypeList = res.data.data;
                  that.form.channelType = that.aa;
                  if (this.form.detailPhoto.length > 9) {
                    this.uploadDisableds = "disabled";
                  }
                  if (this.form.previewPhotos.length > 2) {
                    this.uploadDisabled = "disabled";
                  }
                  that.aa = "";
                  this.bussType()
                } else {
                  that.$notify({
                    title: "错误",
                    message: res.msg,
                    type: "error",
                  });
                }
              })
              .catch((err) => {});
          } else {
            layer.open({
              content: res.data.msg,
              skin: "msg",
              time: 2, //1秒后自动关闭
            });
          }
        })
        .catch((err) => {});
    }
  },
  methods: {
    // 业务类型
    geBusInfo() {
      // 获取业务类型
      https
        .getOfficeAllBusInfo({})
        .then((res) => {
          console.log("业务类型");
          console.log(res);
          this.busOptions = res.data.data
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 业务类型发生变化
    bussType(){
      this.getOfficeBusChannel()
    },
    // 获取业务品牌
    getOfficeBusChannel(){
      https.getOfficeBusChannel({busUid:this.form.busUid}).then(res=>{
        console.log("获取出来的品牌")
        console.log(res)
        this.channelNameList2 = res.data.data
      }).catch(err=>{
        console.log(err)
      })
    },
    // 商品预览图上传成功
    success(res, file, fileList) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.form.previewPhotos.push({ url: res.data.filePath });
      if (this.form.previewPhotos.length > 2) {
        this.uploadDisabled = "disabled";
      }
    },
    handleRemove(res, file, fileList) {
      console.log(res);
      this.uploadDisabled = "";
      for (var i = 0; i < this.form.previewPhotos.length; i++) {
        if (this.form.previewPhotos[i].url == res.url) {
          this.form.previewPhotos.splice(i, 1); //删除下标为i的元素
          return this.form.previewPhotos;
        }
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 商品详情图
    success1(res, file, fileList) {
      // 这里是element的上传地址，对应的name,url,自己打印fileList对照
      this.form.detailPhoto.push({ url: res.data.filePath });
      if (this.form.detailPhoto.length > 9) {
        this.uploadDisableds = "disabled";
      }
    },
    handleRemove1(res, file, fileList) {
      this.uploadDisableds = "";
      console.log(res);
      for (var i = 0; i < this.form.detailPhoto.length; i++) {
        if (this.form.detailPhoto[i].url == res.url) {
          this.form.detailPhoto.splice(i, 1); //删除下标为i的元素
          return this.form.detailPhoto;
        }
      }
    },
    handlePictureCardPreview1(file) {
      this.dialogImageUrl1 = file.url;
      this.dialogVisible1 = true;
    },
    // 点击返回/取消
    back() {
      this.$router.push("commodityManage");
    },
    handleUpdate1(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      // const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        layer.open({
          content: "上传预览图片只能是 jpg、jpeg、png 格式!",
          skin: "msg",
          time: 2,
        });
        return false;
      }
    },
    // 上传校验
    handleUpdate(file) {
      console.log(file);
      let newName = file.name.substring(file.name.lastIndexOf("."));
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg";
      // const isLt2M = file.size / 1024 / 1024 < 1;
      if (!isJPG) {
        layer.open({
          content: "上传预览图片只能是 jpg、jpeg、png 格式!",
          skin: "msg",
          time: 2,
        });
        return false;
      } else {
        let that = this;
        const isSize = new Promise((resolve, reject) => {
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          img.onload = () => {
            let name =
              file.name.substring(0, file.name.lastIndexOf(".")) +
              "_" +
              img.width +
              "_" +
              img.height +
              newName;
            file = new File([file], name);
            const valid = this.$commit.ImageRestrictions(
              img.width,
              img.height,
              1
            );
            valid ? resolve() : reject();
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            layer.open({
              content: "图片尺寸限制为345：140。",
              skin: "msg",
              time: 2,
            });
            return Promise.reject();
          }
        );
        return isSize;
      }
    },
    // 点击完成
    complete() {
      if (this.$route.query.productUid) {
        this.form.productUid = this.$route.query.productUid;
      }
      let that = this;
      if (that.form.detailPhoto.length < 1) {
        return layer.open({
          content: "至少上传一张详情图片",
          skin: "msg",
          time: 2, //2秒后自动关闭
        });
      }
      if (that.form.previewPhotos.length < 1) {
        return layer.open({
          content: "至少上传一张预览图片",
          skin: "msg",
          time: 2, //2秒后自动关闭
        });
      }
      setTimeout(() => {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            https.addShows(that.form).then((res) => {
              if (res.data.code == "0000") {
                if (that.operaTypeStatus) {
                  that.operaTypeStatus = false;
                  return true;
                } else {
                  layer.open({
                    content: "成功",
                    skin: "msg",
                    time: 2, //2秒后自动关闭
                  });
                  that.$router.push("commodityManage");
                }
              } else {
                return layer.open({
                  content: res.data.msg,
                  skin: "msg",
                  time: 2, //2秒后自动关闭
                });
              }
            });
          }
        });
      }, 300);
    },
  },
};
</script>

<style rel="stylesheet/scss">
.disabled .el-upload--picture-card {
  display: none;
}
</style>
<style scoped>
.el-upload--picture-card {
  background-color: #fbfdff;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  width: 148px;
  height: 148px;
  line-height: 146px;
  vertical-align: top;
}
.con {
  position: relative;
}
.contbox6_10 {
  width: 100%;
  overflow-x: auto;
  box-sizing: border-box;
  float: left;
}
.content {
  float: left;
  margin-top: 200px;
  margin-bottom: 0px;
  margin: 36px 0px 0px;
  height: calc(100vh - 100px - 50px);
  overflow-x: auto;
  overflow-y: auto;
  background: #fff;
}
/deep/ .el-input {
  width: 300px;
}
/deep/ .el-select > .el-input {
  width: 300px;
}
/deep/ .el-input__inner {
  width: 300px;
}
.el-form-item {
  width: 450px;
  margin-right: 40px;
}
.el-textarea {
  width: 790px;
}
.el-dropdown {
  margin-top: 0px;
  margin-left: 6px;
}
.el-textarea__inner {
  min-height: 100px !important;
}
.el-button {
  padding: 12px 20px;
}
.buttons {
  float: left;
  margin-top: 80px;
}
.el-form-item {
  margin-bottom: 20px;
}
/deep/ .el-cascader {
  line-height: 32px;
}
</style>
